<?php
namespace Lm\Controllers;

use Helpers\Main;
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;

class ControllerBase extends Controller
{
    public function praseLog($detail,$msg)
    {
        return Main::createCommitLog(
            'lm',
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getActionName(),
            ['post' => $this->request->getPost(), 'get' => $this->request->getQuery(), 'detail' => $detail],
            null,
            $msg
        );
    }
    

    public function beforeExecuteRoute($dispatcher)
    {
        // 这个方法会在每一个能找到的action前执行
        $userId=Main::getLoginUserInfo('userId');
        if(!$userId){
            Main::goLoginPage();
        }
    }

    public function sendSuccessResponse($msg,$praseLog=true){
        if($praseLog){
            $this->praseLog($msg,$msg);
        }
        return $this->response->setContent($msg);
    }

    /**
     *
     *
     * @param $code
     * @param $msg
     * @param bool $praseLog
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * 
     */
    public function sendErrorResponse($code,$msg,$praseLog=true){
        if($praseLog){
            $this->praseLog($code.$msg,$msg);
        }
        return $this->response->setStatusCode($code)->setContent($msg);
    }

    public function sendJsonResponse($data,$praseLog=false,$msg=''){
        if($praseLog){
            $this->praseLog($msg,$msg);
        }
        return $this->response->setContent(json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    public function sendViewError($error)
    {
        $this->view->disableLevel([
            View::LEVEL_LAYOUT,
            View::LEVEL_BEFORE_TEMPLATE,
            View::LEVEL_AFTER_TEMPLATE,
            View::LEVEL_ACTION_VIEW,
        ]);
        return $this->flash->error($error);
    }

    public function sendViewSuccess($msg)
    {
        $this->view->disableLevel([
            View::LEVEL_LAYOUT,
            View::LEVEL_BEFORE_TEMPLATE,
            View::LEVEL_AFTER_TEMPLATE,
            View::LEVEL_ACTION_VIEW,
        ]);
        return $this->flash->success($msg);
    }

}
